﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Configuration;
using System.Net.NetworkInformation;
using System.Diagnostics;

namespace KTDS_IPBS_WEB
{
    public struct InfoTraceroute
    {
        public int Num_Hop;
        public String EndPoint;
        public int StartTime;
        public int StopTime;
        public int ProcessTime;
        public String Info_Message;
        public String Hostname;
    }

    class C_Traceroute
    {
        private const string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

        public List<string> GetTraceRoute(string hostNameOrAddress)
        {
            return GetTraceRoute(hostNameOrAddress, 1);
        }
        private static List<string> GetTraceRoute(string hostNameOrAddress, int ttl)
        {
            Ping pinger = new Ping();
            PingOptions pingerOptions = new PingOptions(ttl, true);
            int timeout = 10000;
            byte[] buffer = Encoding.ASCII.GetBytes(Data);
            PingReply reply = default(PingReply);

            reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);

            List<string> result = new List<string>();
            if (reply.Status == IPStatus.Success)
            {
                result.Add(reply.Address.ToString().Replace('{',' ').Replace('}',' ').Trim());
            }
            else if (reply.Status == IPStatus.TtlExpired)
            {
                //add the currently returned address
                result.Add(reply.Address.ToString().Replace('{', ' ').Replace('}', ' '));
                //recurse to get the next address...
                List<string> tempResult = default(List<string>);
                tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1);
                result.AddRange(tempResult);
            }
            else
            {
                //failure 
            }

            return result;
        }
    }
}